package com.red.wood.common.util;

public class SqlParser {

	/**
	 * 传入多个查询条件,paramStr中的key必须对应
	 * @param sql select * from table where id = ${id} and name = ${name}
	 * @param paramStr new String[]{"id","name"}
	 * @param objValue new Object[]{1,"小张"}
	 * @return
	 */
	public static String getSql(String sql,String[] paramStr,Object[] objValue) {
		if(paramStr == null || objValue == null || !(paramStr.length == objValue.length)) {
			throw new RuntimeException("请核查入参参数！");
		}
		for(int i = 0 ; i < paramStr.length ; i++) {
			StringBuffer valueStr = new StringBuffer();
			if(objValue[i] instanceof String) {
				valueStr.append("'").append(objValue[i]).append("'");
			}else {
				valueStr.append(CommonUtils.valueOf(objValue[i]));
			}
			sql = sql.replace("${"+paramStr[i]+"}", valueStr);
		}
		return sql;
	}
	
	/**
	 * 传入一个查询条件
	 * @param sql select * from table where id = $id
	 * @param paramStr id
	 * @param objValue 1001
	 * @return
	 */
	public static String getSql(String sql,String paramStr,Object objValue) {
		StringBuffer valueStr = new StringBuffer();
		if(objValue instanceof String) {
			valueStr.append("'").append(objValue).append("'");
		}else {
			valueStr.append(CommonUtils.valueOf(objValue));
		}
		sql = sql.replace("$"+paramStr, valueStr);
		return sql;
	}
	
	/**
	 * @param sql:  select ? as user_name,? as ic,province from table where id  > ? and name = ?
	 * @param args: 【new Object[] {"张三",1001,1,"zs"}】 or【"张三",1001,1,"zs"】
	 * @return
	 * @throws Exception
	 */
	public String sqlParameterParse(String sql,Object... args) throws Exception {
		//统计问号个数
		int count = (sql.length() - sql.replace("?","").length()) / 1;
		if(count != args.length) throw new Exception("传参个数未对应！");
		
		sql = sql.replaceAll("\\s{1,}"," ");
		for(Object obj : args) {
			if(obj instanceof String) {
				sql = sql.replaceFirst("\\?","'"+obj+"'");
			}else {
				sql = sql.replaceFirst("\\?",obj+"");
			}
		}
		return sql;
	}
	
	/**
	 * 替换参数,原样替换
	 * @param sql select * from ${database}.table 
	 * @param paramStr database
	 * @param paramValue isdms
	 * @return
	 */
	public static String getOriginalOutputSql(String sql,String paramStr,String paramValue) {
		sql = sql.replace("${"+paramStr+"}", paramValue);
		return sql;
	}
}
